package com.weavernorth.action.application;


import com.weavernorth.action.application.entity.repeatEntity;
import com.weavernorth.util.Logger4jUtil;
import org.apache.log4j.Logger;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.*;


/**
 * 判断时间是否存在重复
 */
public class CheckTimeRepeatOverTimeAction implements Action {
//    private static Log log = LogFactory.getLog(CheckTimeRepeatOverTimeAction.class);
private Logger log= Logger4jUtil.getLoggerByName("/action/CheckTimeRepeatOverTimeAction/");
public String strDates="";
    @Override
    public String execute(RequestInfo requestInfo) {
        log.info("加班申请流程校验时间是否重复：");
        //请求id
        String strRequestid = requestInfo.getRequestid();
        //表名
       // String strTable = requestInfo.getRequestManager().getBillTableName();
        RecordSet rsTable=new RecordSet();
        String strTable ="";
        rsTable.execute("select tablename  from workflow_bill where id = (select formid from workflow_base where id=(select workflowid from workflow_requestbase  where requestid='"+strRequestid+"') and isbill=1)");
        if(rsTable.next()){
            strTable=rsTable.getString("tablename");
        }
        //数据库操作
        RecordSet rs = new RecordSet();
        RecordSet rsLeave = new RecordSet();
        //获取当前流程所有明细表的申请人
        String sql = "select fmd.detail_resourceId userid,hr.lastname username,fmd.detail_fromDate,fmd.detail_toDate,fmd.jhjbkssj jhkssj,fmd.jhjbjssj jhjssj  from " + strTable + "  fm," + strTable + "_dt1 fmd,hrmresource hr where hr.id=fmd.detail_resourceId and fm.id=fmd.mainid and  fm.requestid=? ";
        log.info("得到当前流程的申请人sql:" + sql + ";requestid:" + strRequestid);
        rs.executeQuery(sql, strRequestid);
        List<repeatEntity> list_form=new ArrayList<>();
        while (rs.next()) {
            //申请人
            String strUserid = Util.null2String(rs.getString("userid"));
            //姓名
            String strUserName = Util.null2String(rs.getString("username"));
            //开始日期 时间
            String strBegenDate = Util.null2String(rs.getString("detail_fromDate"))+" "+ Util.null2String(rs.getString("jhkssj"));
            //结束日期时间
            String strEndDate = Util.null2String(rs.getString("detail_toDate"))+" "+ Util.null2String(rs.getString("jhjssj"));
            repeatEntity entity=new repeatEntity();
            entity.setUserid(strUserid);
            entity.setUsername(strUserName);
            entity.setBeginTime(strBegenDate);
            entity.setEndTime(strEndDate);
            list_form.add(entity);
        }
        try {
            Map<String, List<repeatEntity>> mapList = list_form.stream().collect(Collectors.<repeatEntity, String>groupingBy(repeatEntity::getUserid));
            log.info("分组后的数据："+mapList.toString());
            for (String s : mapList.keySet()) {
                //获取员工的记录,升序排序
                List<repeatEntity> list = mapList.get(s).stream().sorted(Comparator.comparing(repeatEntity::getBeginTime)).collect(toList());
                String strBeginDate=list.get(0).beginTime;
                if(strBeginDate.length()>10){
                    strBeginDate=strBeginDate.substring(0,10);
                }
                log.info("人员:"+s+"在表单中最小加班开始日期为："+strBeginDate);
                String message[] = compareTimes(list).split("\\|");
                log.info("状态："+message[0]);
                log.info("信息："+message[1]);
                if(message[0].equals("false")){
                    requestInfo.getRequestManager().setMessagecontent(message[1]);
                    return FAILURE_AND_CONTINUE;
                }else{
                    //当前申请人的所有请假记录,由于历史记录存在重复数据不好排查，因此判断2020-09-01之后的数据
                    String strLeaveSql = "select hr.lastname ,fmd.detail_fromDate,fmd.detail_fromTime,fmd.detail_toDate ,fmd.detail_toTime" +
                            " from " + strTable + " fm ," + strTable + "_dt1 fmd,hrmresource hr,workflow_requestbase wr where " +
                            " fm.requestid=wr.requestid and fm.id=fmd.mainid  and " +
                            "hr.id=fmd.detail_resourceId and (wr.currentnodetype !='0' or wr.requestid=?) and   fmd.detail_resourceId=? AND fmd.detail_fromDate>='"+strBeginDate+"'";
                    log.info("查询数据sql:"+strLeaveSql);
                    log.info("得到所有的日期sql:" + strLeaveSql + ",strUserid:" + s);
                    rsLeave.executeQuery(strLeaveSql, strRequestid, s);
                    List<repeatEntity> list_history=new ArrayList<>();
                    while (rsLeave.next()) {
                        //开始日期时间
                        String strBegin = Util.null2String(rsLeave.getString("detail_fromDate")) +" "+ Util.null2String(rsLeave.getString("detail_fromTime"));
                        log.info("开始日期时间:" + strBegin);
                        //结束日期时间
                        String strEnd = Util.null2String(rsLeave.getString("detail_toDate")) +" "+ Util.null2String(rsLeave.getString("detail_toTime"));
                        log.info("结束日期时间:" + strEnd);
                        String strLastName = Util.null2String(rsLeave.getString("lastname"));
                        repeatEntity entity=new repeatEntity();
                        entity.setUserid(s);
                        entity.setUsername(strLastName);
                        entity.setBeginTime(strBegin);
                        entity.setEndTime(strEnd);
                        list_history.add(entity);
                    }
                    //获取员工的历史记录,升序排序
                    list_history.sort(Comparator.comparing(repeatEntity::getBeginTime));
                    log.info("人员加班历史记录："+list_history.toString());
                    String message_old[] = compareTimes(list_history).split("\\|");
                    if(message_old[0].equals("false")) {
                        requestInfo.getRequestManager().setMessagecontent(message_old[1]);
                        return FAILURE_AND_CONTINUE;
                    }
                }

            }
        }catch (Exception ex){
            log.info("程序异常,异常信息："+ex.toString());
            requestInfo.getRequestManager().setMessagecontent("程序异常,异常信息："+ex.toString());
            return FAILURE_AND_CONTINUE;
        }

        return SUCCESS;
    }
    /**
     * 对比两个list的时间是否存在重复
     *
     * @param list
     * @return
     */
    public String compareTimes(List<repeatEntity> list) {
        log.info("要比较的数据："+list.toString());
        //返回值
        String result = "true|无重复记录！";
        try {
            for (int i = 0; i < list.size(); i++) {
                String d1 = list.get(i).endTime;
                if(d1.length()<12) {
                    log.info("人员："+ list.get(i).getUsername()+"在"+d1+"存在未打卡情况！");
                    result = "false|人员："+ list.get(i).getUsername()+"在"+d1+"存在未打卡情况！";
                    break;
                }else{
                    log.info("结束时间：" + d1);
                    SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    Date enddate1 = formater.parse(d1);
                    for (int j = i + 1; j < list.size(); j++) {
                        String d2 = list.get(j).beginTime;
                        log.info("开始时间：" + d2);
                        Date startdate2 = formater.parse(d2);
                        if (!startdate2.after(enddate1)) {
                            result = "false|人员" + list.get(i).getUsername() + "在" + list.get(i).getBeginTime().substring(0, 11) + "存在重复记录！";
                            log.info(result);
                            break;
                        }
                        if (startdate2.after(enddate1)) {
                            log.info(list.get(i) + "与" + list.get(j) + "不重合");
                        }
                    }
                }
            }
        }catch (Exception ex){
            log.info("时间对比异常："+ex.toString());
            result = "false|时间对比异常："+ex.toString();
        }
        return result;
    }
    /**
     * 对比两个list的时间是否存在重复
     *
     * @param listBegin
     * @param listEnd
     * @return
     */
    public boolean compareTime(List<String> listBegin, List<String> listEnd) {
        //返回值
        boolean bolFlag = true;
        RecordSet rs = new RecordSet();
        BaseBean bb = new BaseBean();
        //升序排序
        Collections.sort(listBegin);
        Collections.sort(listEnd);
        //判断是否存在重叠
        if (listBegin.size() > 1) {
            //开始日期时间的下一行数据是否小于结束日期时间的上一行,小于则重叠
            for (int i = 1; i < listBegin.size(); i++) {
                //开始日期时间
                String strBegin = listBegin.get(i);
                //结束时间日期
                String strEnd = listEnd.get(i - 1);
                if (strBegin.compareTo(strEnd) < 0) {
                    bolFlag = false;
                    strDates=strBegin;
                    log.info("重复的时间段:"+strBegin+",strEnd:"+strEnd);
                    //当存在时间重复时,判断此流程有无销假数据
//                    String strBackTable = Util.null2String(bb.getPropValue("attendMess", "backTimeTable"));
//                    String strSql = "select * from " + strBackTable + " fm," + strBackTable + "_dt1 fmd,workflow_requestbase wr where fm.requestid=wr.requestid and  wr.currentnodetype=3 and fm.id=fmd.mainid and fm.resourceId=?";
//                    log.info("查询销假流程:"+strSql+",strUserid:"+strUserid);
//                    rs.executeQuery(strSql, strUserid);
//                    while (rs.next()) {
//                        //销假开始日期时间
//                        String strDetail_fromDate = Util.null2String(rs.getString("detail_fromDate")) + Util.null2String(rs.getString("detail_fromTime"));
//                        log.info("销假开始时间:"+strDetail_fromDate);
//
//                        //销假开结束日期时间
//                        String strDetail_toDate = Util.null2String(rs.getString("detail_toDate")) + Util.null2String(rs.getString("detail_toTime"));
//                        log.info("销假结束时间:"+strDetail_toDate);
//                        if (strDetail_fromDate.compareTo(strBegin) <= 0 && strDetail_toDate.compareTo(strEnd) >= 0) {
//                            bolFlag = true;
//                            break;
//                        }
//
//                    }


                    //   bolFlag = false;
                }
            }
        }
        return bolFlag;
    }

//    //存放所有的开始日期时间list
//    List<String> listBegin = new ArrayList<String>();
//    //存放所有的结束日期时间list
//    List<String> listEnd = new ArrayList<String>();
//    //当前申请人的所有请假记录,由于历史记录存在重复数据不好排查，因此判断2020-09-01之后的数据
//    String strLeaveSql = "select hr.lastname ,fmd.detail_fromDate,fmd.detail_fromTime,fmd.detail_toDate ,fmd.detail_toTime" +
//            " from " + strTable + " fm ," + strTable + "_dt1 fmd,hrmresource hr,workflow_requestbase wr where " +
//            " fm.requestid=wr.requestid and fm.id=fmd.mainid  and " +
//            "hr.id=fmd.detail_resourceId and (wr.currentnodetype !='0' or wr.requestid=?) and   fmd.detail_resourceId=? AND fmd.detail_fromDate>'2020-09-01'";
//            log.info("查询数据sql:"+strLeaveSql);
//            log.info("得到所有的日期sql:" + strLeaveSql + ",strUserid:" + strUserid);
//            rsLeave.executeQuery(strLeaveSql, strRequestid, strUserid);
//            while (rsLeave.next()) {
//        //开始日期时间
//        String strBegin = Util.null2String(rsLeave.getString("detail_fromDate")) + Util.null2String(rsLeave.getString("detail_fromTime"));
//        log.info("开始日期时间:" + strBegin);
//        listBegin.add(strBegin);
//        //结束日期时间
//        String strEnd = Util.null2String(rsLeave.getString("detail_toDate")) + Util.null2String(rsLeave.getString("detail_toTime"));
//        log.info("结束日期时间:" + strEnd);
//        listEnd.add(strEnd);
//        strLastName = Util.null2String(rsLeave.getString("lastname"));
//    }
//    //对比list是否存在重复
//    boolean bolFlag = compareTime(listBegin, listEnd);
//            log.info("重复判断返回结果:" + bolFlag);
//    //存在重复
//            if (!bolFlag) {
//        requestInfo.getRequestManager().setMessagecontent("您申请的流程中,姓名为:" + strLastName + "的用户"+strDates+"存在重复记录");
//        return FAILURE_AND_CONTINUE;
//    }
}